package com.swak.threads.utilization;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import net.openhft.affinity.AffinityLock;

public class EventLoop {

	Wait waitStrategy;
	Thread thread;
	BlockingQueue<Runnable> taskQueue;

	public EventLoop(Wait waitStrategy) {
		this.taskQueue = new LinkedBlockingQueue<Runnable>();
		this.waitStrategy = waitStrategy;
		this.thread = new Thread(this::run, "EventLoop");
		this.thread.start();
	}

	private void run() {
		try (AffinityLock lock = AffinityLock.acquireLock(15)) {
			System.out.println("Run EventLoop on CPU " + lock.cpuId());

			while (true) {

				// 1. 这是等待策略
				try {
					waitStrategy.waitFor(this.taskQueue);
				} catch (Exception e) {
				}

				// 2. 这是业务代码

			}
		}
	}
}